package com.lei.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.eduservice.entity.EduChapter;
import com.lei.eduservice.entity.EduVideo;
import com.lei.eduservice.entity.chapter.ChapterVo;
import com.lei.eduservice.entity.chapter.VideoVo;
import com.lei.eduservice.mapper.EduChapterMapper;
import com.lei.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lei.eduservice.service.EduVideoService;
import com.lei.servicebase.exception.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 熊磊
 * @since 2020-06-04
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService videoService;
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        //1.根据课程Id查出所有章节
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(wrapper);

        //2.根据课程Id查出所有小节
        QueryWrapper<EduVideo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("course_id",courseId);
        List<EduVideo> eduVideos = videoService.list(wrapper1);

        ArrayList<ChapterVo> finalChapter = new ArrayList<>();

        //3.根据课程章节ID查出对应的小节,并进行封装
        for (EduChapter eduChapter : eduChapters) {
            //用BeanUtils将查询出来的章节，copy为ChapterVo用于前端交互
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            //遍历出ChapterVo的children,VideoVos
            for (EduVideo eduVideo : eduVideos) {
                if (eduVideo.getChapterId().equals(eduChapter.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(eduVideo,videoVo);
                    chapterVo.getChildren().add(videoVo);
                }

            }
            //将chapterVo放入finalChapter
            finalChapter.add(chapterVo);
        }

        return finalChapter;
    }

    //判断章节是否能删除并进行删除操作
    @Override
    public boolean deleteChapter(String chapterId) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);
        if (videoService.count(wrapper)>0){
            throw new GuliException(20001,"该章节存在小节,无法删除");
        }else {
            int result = baseMapper.deleteById(chapterId);
            return result>0;
        }

    }

    @Override
    public void removeByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }
}
